/**
 * 景区AI助手组件
 * 集成coze智能导游和商铺活动BOT功能
 */

'use client'

import React, { useState, useEffect, useRef, useCallback } from 'react'
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Bot, Send, X, MapPin, ShoppingBag, Coffee, Utensils } from 'lucide-react'
import { toast } from 'sonner'
import { getStoresByAttraction } from '@/lib/api/store'
import { getFacilitiesByAttraction } from '@/lib/api/facility'

interface AIMessage {
  id: string
  type: 'user' | 'assistant'
  content: string
  timestamp: Date
  actions?: Array<{
    type: 'navigate' | 'info' | 'promotion'
    label: string
    data: any
  }>
}

interface AttractionAIAssistantProps {
  attractionId?: string
  className?: string
  onNavigateTo?: (location: { lng: number; lat: number }) => void
  onStoreSelect?: (store: any) => void
}

export const AttractionAIAssistant: React.FC<AttractionAIAssistantProps> = ({
  attractionId,
  className = '',
  onNavigateTo,
  onStoreSelect
}) => {
  const [isOpen, setIsOpen] = useState(false)
  const [activeBot, setActiveBot] = useState<'guide' | 'activity'>('guide')
  const [messages, setMessages] = useState<AIMessage[]>([])
  const [inputValue, setInputValue] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const [stores, setStores] = useState<any[]>([])
  const [facilities, setFacilities] = useState<any[]>([])
  const messagesEndRef = useRef<HTMLDivElement>(null)

  // AI响应模板 - 景区专用
  const aiResponses = {
    guide: {
      greeting: '您好！我是智能导游助手，可以帮您:\n• 🗺️ 景区导航\n• 🏗️ 设施查找\n• 📍 位置指引\n• ℹ️ 景区介绍\n\n请问需要什么帮助？',
      navigation: '我来为您导航到{location}，请跟随地图上的路线指示。',
      facility: '为您找到了{facility}的位置信息',
      info: '关于{topic}的详细信息如下',
      fallback: '抱歉，我没有完全理解您的问题。您可以询问景区导航、设施位置或景区介绍等。'
    },
    activity: {
      greeting: '您好！我是商业活动助手，可以为您提供:\n• 🍽️ 餐饮推荐\n• 🛍️ 购物指南\n• ☕ 休闲服务\n• 🎉 优惠活动\n\n有什么可以帮您的吗？',
      recommendation: '根据您的需求，为您推荐以下商铺',
      promotion: '发现优惠活动！',
      service: '为您提供相关服务信息',
      fallback: '抱歉，我没有理解您的需求。您可以询问餐饮、购物、服务等信息。'
    }
  }

  // 预设的商铺关键词映射（模拟coze的工作流）
  const storeKeywords = {
    '肯德基': {
      name: 'KFC肯德基',
      promotion: '🍗 新品上市！\n\n📍 位置：美食广场2楼\n⏰ 营业时间：10:00-22:00\n📞 电话：400-882-3823\n\n🎉 当前活动：\n• 黄金鸡块买一送一\n• 全家桶8折优惠\n• 新会员注册送薯条\n\n立即前往享受美食吧！',
      business: 'restaurant',
      location: { lng: 120.1563, lat: 30.2753 }
    },
    '星巴克': {
      name: 'Starbucks星巴克',
      promotion: '☕ 咖啡时光！\n\n📍 位置：景区入口处\n⏰ 营业时间：07:00-23:00\n\n🎉 限时优惠：\n• 第二杯半价\n• 会员积分双倍\n• 季节特饮新上市\n\n来一杯暖心咖啡吧！',
      business: 'cafe',
      location: { lng: 120.1564, lat: 30.2754 }
    },
    '便利店': {
      name: '全家便利店',
      promotion: '🏪 24小时便民服务！\n\n📍 位置：景区中心广场\n⏰ 营业时间：24小时\n\n🛍️ 服务项目：\n• 日用品采购\n• 热饮热食\n• 手机充电\n• 休息座椅\n\n您的贴心生活助手！',
      business: 'shopping',
      location: { lng: 120.1565, lat: 30.2755 }
    }
  }

  // 设施关键词映射
  const facilityKeywords = {
    '卫生间': {
      name: '公共卫生间',
      info: '🚻 为您找到最近的卫生间\n\n📍 多个位置可选：\n• 景区入口处\n• 美食广场旁\n• 游客中心内\n• 停车场附近\n\n♿ 无障碍设施齐全',
      type: 'toilet'
    },
    'ATM': {
      name: 'ATM取款机',
      info: '🏧 ATM服务点\n\n📍 位置：游客中心大厅\n💳 支持银联卡取款\n⏰ 24小时服务\n\n💰 单次取款限额：3000元',
      type: 'atm'
    },
    '停车场': {
      name: '停车服务',
      info: '🅿️ 停车场信息\n\n📍 主要停车区域：\n• 东门停车场（500个车位）\n• 西门停车场（300个车位）\n• 地下停车场（200个车位）\n\n💰 收费标准：前2小时免费，之后5元/小时',
      type: 'parking'
    }
  }

  // 加载景区数据
  const loadAttractionData = useCallback(async () => {
    if (!attractionId) return

    try {
      const [storesResult, facilitiesResult] = await Promise.all([
        getStoresByAttraction(attractionId),
        getFacilitiesByAttraction(attractionId)
      ])

      if (storesResult.success && storesResult.data) {
        setStores(storesResult.data)
      }

      if (facilitiesResult.success && facilitiesResult.data) {
        setFacilities(facilitiesResult.data)
      }
    } catch (error) {
      console.error('加载景区数据失败:', error)
    }
  }, [attractionId])

  useEffect(() => {
    loadAttractionData()
  }, [loadAttractionData])

  useEffect(() => {
    scrollToBottom()
  }, [messages])

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
  }

  // 初始化对话
  useEffect(() => {
    if (isOpen && messages.length === 0) {
      const welcomeMessage: AIMessage = {
        id: `msg_${Date.now()}`,
        type: 'assistant',
        content: aiResponses[activeBot].greeting,
        timestamp: new Date()
      }
      setMessages([welcomeMessage])
    }
  }, [isOpen, activeBot])

  // 智能意图识别
  const analyzeMessage = (message: string) => {
    const normalizedMessage = message.toLowerCase()
    
    // 商铺查询意图
    for (const [keyword, storeInfo] of Object.entries(storeKeywords)) {
      if (normalizedMessage.includes(keyword.toLowerCase())) {
        return {
          intent: 'store_query',
          entity: storeInfo,
          keyword
        }
      }
    }

    // 设施查询意图
    for (const [keyword, facilityInfo] of Object.entries(facilityKeywords)) {
      if (normalizedMessage.includes(keyword.toLowerCase()) || 
          normalizedMessage.includes(facilityInfo.name.toLowerCase())) {
        return {
          intent: 'facility_query',
          entity: facilityInfo,
          keyword
        }
      }
    }

    // 导航意图
    if (normalizedMessage.includes('在哪') || normalizedMessage.includes('怎么走') || 
        normalizedMessage.includes('位置') || normalizedMessage.includes('导航')) {
      return { intent: 'navigation', entity: null }
    }

    // 推荐意图
    if (normalizedMessage.includes('推荐') || normalizedMessage.includes('什么好吃') || 
        normalizedMessage.includes('逛街') || normalizedMessage.includes('购物')) {
      return { intent: 'recommendation', entity: null }
    }

    // 优惠活动意图
    if (normalizedMessage.includes('活动') || normalizedMessage.includes('优惠') || 
        normalizedMessage.includes('折扣') || normalizedMessage.includes('促销')) {
      return { intent: 'promotion', entity: null }
    }

    return { intent: 'unknown', entity: null }
  }

  // 生成AI响应
  const generateResponse = (message: string, analysis: any): AIMessage => {
    const { intent, entity, keyword } = analysis

    let content = ''
    let actions: any[] = []

    switch (intent) {
      case 'store_query':
        if (activeBot === 'activity') {
          content = entity.promotion
          actions = [
            {
              type: 'navigate',
              label: '🗺️ 前往导航',
              data: entity.location
            },
            {
              type: 'info',
              label: 'ℹ️ 详细信息',
              data: entity
            }
          ]
        } else {
          content = `为您找到了${entity.name}的位置信息。如需了解优惠活动，请切换到商业助手。`
          actions = [
            {
              type: 'navigate',
              label: '🗺️ 前往导航',
              data: entity.location
            }
          ]
        }
        break

      case 'facility_query':
        content = entity.info
        const facility = facilities.find(f => f.type === entity.type)
        if (facility) {
          actions = [
            {
              type: 'navigate',
              label: '🗺️ 前往导航',
              data: { lng: facility.position[0], lat: facility.position[1] }
            }
          ]
        }
        break

      case 'recommendation':
        if (activeBot === 'activity') {
          const randomStores = stores.slice(0, 3)
          content = `${aiResponses.activity.recommendation}：\n\n${randomStores.map((store, index) => 
            `${index + 1}. 🏪 ${store.name}\n   📍 ${store.business === 'restaurant' ? '餐饮' : store.business === 'cafe' ? '咖啡' : '购物'}`
          ).join('\n\n')}`
          
          actions = randomStores.map(store => ({
            type: 'info',
            label: `📍 ${store.name}`,
            data: store
          }))
        } else {
          content = '我是导游助手，主要负责导航服务。如需商铺推荐，请切换到商业助手。'
        }
        break

      case 'promotion':
        if (activeBot === 'activity') {
          content = `${aiResponses.activity.promotion}\n\n🎉 当前热门活动：\n• KFC黄金鸡块买一送一\n• 星巴克第二杯半价\n• 便利店满50减10\n\n更多优惠等您发现！`
        } else {
          content = '我是导游助手，如需了解商业活动，请切换到商业助手。'
        }
        break

      case 'navigation':
        content = '请告诉我您想去的具体位置，比如"卫生间在哪"、"肯德基怎么走"等，我来为您导航。'
        break

      default:
        content = aiResponses[activeBot].fallback
        break
    }

    return {
      id: `msg_${Date.now()}_ai`,
      type: 'assistant',
      content,
      actions,
      timestamp: new Date()
    }
  }

  // 发送消息
  const sendMessage = async () => {
    if (!inputValue.trim()) return

    const userMessage: AIMessage = {
      id: `msg_${Date.now()}_user`,
      type: 'user',
      content: inputValue,
      timestamp: new Date()
    }

    setMessages(prev => [...prev, userMessage])
    setInputValue('')
    setIsLoading(true)

    // 模拟AI处理时间
    setTimeout(() => {
      const analysis = analyzeMessage(inputValue)
      const aiResponse = generateResponse(inputValue, analysis)
      setMessages(prev => [...prev, aiResponse])
      setIsLoading(false)
    }, 1000)
  }

  // 处理快捷建议
  const handleSuggestionClick = (suggestion: string) => {
    setInputValue(suggestion)
    setTimeout(() => sendMessage(), 100)
  }

  // 处理动作按钮
  const handleActionClick = (action: any) => {
    switch (action.type) {
      case 'navigate':
        onNavigateTo?.(action.data)
        toast.success('正在为您导航...')
        break
      case 'info':
        onStoreSelect?.(action.data)
        break
      case 'promotion':
        toast.success('优惠信息已展示')
        break
    }
  }

  // 切换机器人类型
  const switchBot = (bot: 'guide' | 'activity') => {
    setActiveBot(bot)
    setMessages([]) // 清空对话
  }

  // 快捷建议
  const getSuggestions = () => {
    if (activeBot === 'guide') {
      return ['卫生间在哪', 'ATM在哪里', '停车场位置', '景区介绍']
    } else {
      return ['肯德基', '星巴克', '有什么好吃的', '当前有什么活动']
    }
  }

  if (!isOpen) {
    return (
      <div className={`fixed bottom-4 right-4 z-50 ${className}`}>
        <Button
          onClick={() => setIsOpen(true)}
          size="lg"
          className="rounded-full w-14 h-14 shadow-lg bg-gradient-to-r from-blue-500 to-purple-600 hover:from-blue-600 hover:to-purple-700"
        >
          <Bot className="w-6 h-6" />
        </Button>
      </div>
    )
  }

  return (
    <div className={`fixed bottom-4 right-4 w-96 h-[600px] bg-white rounded-lg shadow-2xl border z-50 flex flex-col ${className}`}>
      {/* 头部 */}
      <CardHeader className="pb-3 border-b">
        <div className="flex items-center justify-between">
          <CardTitle className="text-lg flex items-center gap-2">
            <Bot className="w-5 h-5" />
            景区AI助手
          </CardTitle>
          <Button
            variant="ghost"
            size="sm"
            onClick={() => setIsOpen(false)}
            className="h-8 w-8 p-0"
          >
            <X className="w-4 h-4" />
          </Button>
        </div>
        
        {/* 机器人切换 */}
        <Tabs value={activeBot} onValueChange={(value: any) => switchBot(value)} className="w-full">
          <TabsList className="grid w-full grid-cols-2 h-8">
            <TabsTrigger value="guide" className="text-xs gap-1">
              <MapPin className="w-3 h-3" />
              智能导游
            </TabsTrigger>
            <TabsTrigger value="activity" className="text-xs gap-1">
              <ShoppingBag className="w-3 h-3" />
              商业助手
            </TabsTrigger>
          </TabsList>
        </Tabs>
      </CardHeader>

      {/* 消息区域 */}
      <CardContent className="flex-1 overflow-y-auto p-4 space-y-3">
        {messages.map((message) => (
          <div
            key={message.id}
            className={`flex ${message.type === 'user' ? 'justify-end' : 'justify-start'}`}
          >
            <div
              className={`max-w-[80%] p-3 rounded-lg text-sm ${
                message.type === 'user'
                  ? 'bg-blue-500 text-white'
                  : 'bg-gray-100 text-gray-800'
              }`}
            >
              <div className="whitespace-pre-wrap">{message.content}</div>
              
              {/* 动作按钮 */}
              {message.actions && message.actions.length > 0 && (
                <div className="flex flex-wrap gap-2 mt-2">
                  {message.actions.map((action, index) => (
                    <Button
                      key={index}
                      variant="outline"
                      size="sm"
                      onClick={() => handleActionClick(action)}
                      className="h-6 px-2 text-xs"
                    >
                      {action.label}
                    </Button>
                  ))}
                </div>
              )}
              
              <div className="text-xs opacity-70 mt-1">
                {message.timestamp.toLocaleTimeString()}
              </div>
            </div>
          </div>
        ))}
        
        {isLoading && (
          <div className="flex justify-start">
            <div className="bg-gray-100 text-gray-800 p-3 rounded-lg text-sm">
              <div className="flex items-center gap-2">
                <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" />
                <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '0.1s' }} />
                <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '0.2s' }} />
                <span>AI思考中...</span>
              </div>
            </div>
          </div>
        )}
        
        <div ref={messagesEndRef} />
      </CardContent>

      {/* 快捷建议 */}
      <div className="px-4 py-2 border-t bg-gray-50">
        <div className="text-xs text-gray-600 mb-2">快捷咨询：</div>
        <div className="flex flex-wrap gap-1">
          {getSuggestions().map((suggestion, index) => (
            <Button
              key={index}
              variant="outline"
              size="sm"
              onClick={() => handleSuggestionClick(suggestion)}
              className="h-6 px-2 text-xs"
            >
              {suggestion}
            </Button>
          ))}
        </div>
      </div>

      {/* 输入区域 */}
      <div className="p-4 border-t">
        <div className="flex gap-2">
          <Input
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            placeholder={`向${activeBot === 'guide' ? '智能导游' : '商业助手'}提问...`}
            onKeyDown={(e) => e.key === 'Enter' && sendMessage()}
            disabled={isLoading}
            className="flex-1"
          />
          <Button onClick={sendMessage} disabled={isLoading || !inputValue.trim()}>
            <Send className="w-4 h-4" />
          </Button>
        </div>
      </div>
    </div>
  )
}